﻿using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase;
using System;
using System.Text;
using IOA.MES.Client.Common;
using NLog;

namespace IOA.MES.Client.Top.TopTcp
{
    public delegate void DelMessageReceived(string ip, string message);
    /// <summary>
    /// 层压机TCP服务
    /// </summary>
    public class TopServer : AppServer<TopSession, StringRequestInfo>
    {
        private DelMessageReceived messageReceived;
        public TopServer(DelMessageReceived messageReceived) : base(new TopReceiveFilterFactory())
        {
            this.messageReceived = messageReceived;
        }

        protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
        {
            this.NewRequestReceived += ElectricMeterServer_NewRequestReceived;
            return base.Setup(rootConfig, config);
        }

        private void ElectricMeterServer_NewRequestReceived(TopSession session, StringRequestInfo requestInfo)
        {
            var orignData = requestInfo.Body;
            CommonMessage.Log(LogLevel.Warn, $"{session.RemoteEndPoint.ToString()} 接收报文：{orignData}");
            try
            {
                if (messageReceived != null)
                {
                    messageReceived(session.RemoteEndPoint.Address.ToString(), orignData);
                }
            }
            catch (Exception ex)
            {
                CommonMessage.Log(LogLevel.Fatal, $"{session.RemoteEndPoint.ToString()} 处理报文异常，报文：{orignData}，异常信息：{ex.Message}", ex);
            }
        }

        private void SendMessage(TopSession session, string message)
        {
            var buffer = Encoding.ASCII.GetBytes(message);
            session.Send(buffer, 0, buffer.Length);
            CommonMessage.Log(LogLevel.Warn, $"{session.RemoteEndPoint.ToString()} 发送报文：{message}");
        }
    }
}
